package com.ghck.server.controller;

import java.security.Principal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ghck.server.controller.access.ArgIndexForPrintLog;
import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.CreditsHistory;
import com.ghck.server.model.query.CreditsHistoryQuery;
import com.ghck.server.model.response.ResultList;
import com.ghck.server.model.response.ResultObject;
import com.ghck.server.security.AjkUserDetails;
import com.ghck.server.service.CreditsHistoryService;
import com.ghck.server.utils.AjkUtil;

@RestController
@RequestMapping("/credits")
public class CreditController {

	@Autowired
	private CreditsHistoryService creditsHistoryService;

	/**
	 * 签到
	 */
	@ArgIndexForPrintLog(indexes = { 1 })
	@RequestMapping(value = "/sign_in", method = RequestMethod.POST)
	public ResultObject<Integer> signIn(Principal principal) {
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if (null == user) {
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		Integer cHistory = creditsHistoryService.signIn(userId);
		return new ResultObject<Integer>(cHistory);
	}

	/**
	 * 是否已签到
	 */
	@ArgIndexForPrintLog(indexes = { 1 })
	@RequestMapping(value = "/today_is_sign", method = RequestMethod.GET)
	public ResultObject<Boolean> godayIsSign(Principal principal) {
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		Boolean result = creditsHistoryService.todayIsSign(userId);
		return new ResultObject<Boolean>(result);
	}

	/**
	 * 阳光值记录列表
	 */
	@ArgIndexForPrintLog(indexes = { 1 })
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResultList<CreditsHistory> findMyCredits(Integer startId, Integer endId, Integer start, Integer limit,
			Principal principal) {
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		CreditsHistoryQuery query = new CreditsHistoryQuery();
		query.setUserId(userId);
		query.setStartId(startId);
		query.setStart(start);
		query.setEndId(endId);
		query.setLimit(limit);
		List<CreditsHistory> list = creditsHistoryService.findCreditsHistoryByQuery(query);
		return new ResultList<CreditsHistory>(list);
	}
}
